package com.zxy.express.interceptor;

import com.autopai.base.common.tools.utils.JsonUtil;
import com.autopai.base.common.web.exception.BusinessException;
import com.autopai.base.common.web.model.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * 校验token
 *
 * @author zhangxiying
 * @version 1.0
 * @date 2025/07/01
 */
@Aspect
@Component
@Slf4j
@Order(Integer.MIN_VALUE)
public class LoggingInterceptor {

    @Pointcut("execution(* com.zxy.express.controller.*.*(..))")
    public void point() {
    }


    @Around("point()")
    public Object aroundCheck(ProceedingJoinPoint joinPoint) throws Throwable {
        String requestId = UUID.randomUUID().toString().replace("-", "");
        MDC.put("requestId", requestId);
        long start = System.currentTimeMillis();
        Object result;
        String methodName = joinPoint.getSignature().getName();
        Class<?> classTarget = joinPoint.getTarget().getClass();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        try {
            String args;
            if ("GET".equals(request.getMethod())) {
                args = request.getQueryString();
            } else {
                Object[] param = joinPoint.getArgs();
                if (param != null && param.length > 0) {
                    args = JsonUtil.obj2String(param[0]);
                } else {
                    args = "";
                }
            }
            log.info("ThreadID:{},MethodName:{},RequestURI:{},Param:{},url:{}",
                    Thread.currentThread().getId(),
                    classTarget.getName() + "." + methodName, request.getRequestURI(), JsonUtil.obj2String(args), request.getRequestURI());
            result = joinPoint.proceed();
            return result;
        } catch (Throwable e) {
            result = e instanceof BusinessException ? new RestResult().error(((BusinessException) e).getCode(),((BusinessException) e).getMsg()) : new RestResult().error();
            long duration = System.currentTimeMillis() - start;
            log.error("ThreadID:{},MethodName:{},Exception:{},Response:{}, TimeCost:{},url:{}",
                    Thread.currentThread().getId(), classTarget.getName() + "." + methodName, ExceptionUtils.getStackTrace(e), result, duration + "ms", request.getRequestURI());
            return result;
        }
    }
}